'''
    Weibo Post methods
'''
import types
from WeiboClient import WeiboClient
from TimeParse import Time
from MySqlDBHandle import MySqlDBHandle

class Post(WeiboClient):
    mSQLStatement = "INSERT INTO Post (Post_id, Message, Minute_id, Comment_Count, Repost_Count, Weibo_id)\
    VALUES %s ON DUPLICATE KEY UPDATE Comment_Count = Values(Comment_Count),\
    Repost_Count = Values(Repost_Count);"
    mSQLValueStatement = "(%s, '%s', %s, %s, %s, %s),"
    
    mAPI = 'statuses/user_timeline'
    
    def __init__(self, iUid):
        self.mUid = iUid
        WeiboClient.__init__(self)
    
    def _sendToDB(self, iJsonData):
        assert(type(iJsonData) == types.ListType)
        lTime = Time()
        
        lValueStatement = ""
        for lPost in iJsonData:
            try:
                #lPost['text'] = lPost['text'].encode('gbk', 'ignore')
                lPost['text'] = lPost['text'].replace("'", "''")
                #print lPost
                #print lPost['id']
                #print lPost['text']
                #print lPost['created_at']
                #print lPost['comments_count']
                lValueStatement = (self.mSQLValueStatement % (lPost['id'], lPost['text'], lTime.getMinuteId(lPost['created_at']),lPost['comments_count'],\
                                                        lPost['reposts_count'], self.mUid))
                
                lSQLStatement = self.mSQLStatement % lValueStatement[:len(lValueStatement) - 1]
                
                #print lSQLStatement
                
                try:
                    MySqlDBHandle.execSqlStatement(lSQLStatement)
                except Exception, e:
                    print "Error in Post.py sendToDB function with error_message = " + str(e)      
            except Exception, e:
                print "Error in Post.py sendToDB function with error_message = " + str(e)
                continue

    def process(self):
        lParams = {}
        lParams['uid'] = self.mUid
        lParams['count'] = 50
        lParams['access_token'] = self.mPublicToken[1]
        #lParams['total_number'] = 50
        
        print ("Get posts for user = %s" % self.mUid)
        lJsonResult = self.fetchUsingAPI(self.mAPI, lParams)
        if type(lJsonResult) == types.ListType and len(lJsonResult) > 0:
            self._sendToDB(lJsonResult)
        print ("Insert posts success !!!")